package com.cjzuji.rental.dao.impl;
import com.alibaba.excel.util.NumberUtils;
import com.cjzuji.rental.dao.AiZuJiOrderDao;
import com.cjzuji.rental.mapper.OrderContractMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.mapper.OrderUserMapper;
import com.cjzuji.rental.pojo.MaterialSpec;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@Service
public class AiZuJiOrderDaoImpl implements AiZuJiOrderDao {
    private static final Pattern STORAGE_PATTERN =
            Pattern.compile("(\\d+[GMT]B?)", Pattern.CASE_INSENSITIVE);
    private static final Logger logger = LoggerFactory.getLogger(AiZuJiOrderDaoImpl.class);
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderUserMapper orderUserMapper;
    @Autowired
    OrderContractMapper orderContractMapper;
    @Override
    @Transactional
    public Long save(Map<String, Object> data, Map<String, Object> detail, int screenStr, double screenRisksAmount,double discountAmount) {
        int idCardStatus = 0;
        if (!data.get("idNo").toString().equals("")) {
            idCardStatus = 1;
        }
        int orderStatus;
        String deliveryNo = "";
        switch (data.get("stateName").toString()) {
            case "待发货":
                orderStatus = 1;
                break;
            case "待归还":
                orderStatus = 3;
                deliveryNo = data.get("logisticsNo").toString();
                break;
            case "逾期":
                orderStatus = 4;
                break;
            case "已完成":
                orderStatus = 5;
                deliveryNo = data.get("logisticsNo").toString();
                break;
            default:
                orderStatus = 7;
                break;
        }
        String assigner =  data.containsKey("remarkOperatorName")?data.get("remarkOperatorName").toString():"";
        String time = data.get("applyTime").toString();
        String remarkCreateTime = DateUtil.longtoStr(Long.parseLong(time)) ;
        String spec = data.get("materielSpecName").toString();
        //logger.info("商品属性："+spec);
        String colour = " ";
        String suk = " ";
        if(spec != null && !spec.isEmpty() ){
            MaterialSpec materialSpec = null ;
            if (!spec.contains("|") || !spec.contains(" ")){
                materialSpec = new MaterialSpec(spec, "");
            }
            if(spec.contains("|")){
                String[] parts = spec.split("\\|");
                materialSpec = getMaterialSpec(parts);
            }
            //空格分割
            if(spec.contains(" ")){
                String[] parts = spec.split("\\s+");
                materialSpec = getMaterialSpec(parts);
            }
            colour = materialSpec.getColor();
            suk = materialSpec.getSuk();
        }
        Orders aiZUJiOrder = Orders.builder()
                .shopId(1)
                .platformId(2)
                .orderId(data.get("rentRecordNo").toString())
                .realName(data.get("realName").toString())    //下单用户
                .phone(data.get("phoneNum").toString())   //下单用户手机号
                .opinion(data.get("riskType").toString())  //风控
                .assigner(assigner)  //分配人 备注人
                //.orderIdTag(data.get("id").toString()) //平台订单ID
                .carBrand(data.get("materielModelName").toString()+data.get("configValue").toString()+data.get("packageName").toString()) //产品备注
                .colour(colour)  //商品属性
                .sku(suk)  //商品SKU
                .actualFiancingAmount((double)data.get("totalRentAmount"))  //总租金 totalRentAmount
                .buyoutAmount(Double.parseDouble(data.get("buyoutAmount").toString()))  //买断价 buyoutAmount
                .discountAmount(discountAmount)
                .monthRepayment((double)data.get("totalRentAmount")/Double.parseDouble(data.get("leaseTerm").toString()))  //月租金
                .bondFreeCreditAmt(Double.parseDouble(data.get("totalRentAmount").toString())+Double.parseDouble(data.get("buyoutAmount").toString())-discountAmount) //订单总金额
                .surplusBondAmt(Double.parseDouble(data.get("depositAmount").toString())) //押金
                .leaseTerm(data.get("leaseTerm").toString())   //订单租期
                .idAuthStatus(idCardStatus)  //身份证上传状态
                .rentStartTime(data.get("leaseTermRange").toString().substring(0,10))  //租赁开始时间
                .rentLastTime(data.get("leaseTermRange").toString().substring(11,21))  //租赁结束时间
                .status(orderStatus)    //订单状态
                .deliveryNo(deliveryNo)  //快递单号
                .createTime(remarkCreateTime)  // 下单时间
                .updateTime(new Date())
                .screenRisksAmount(screenRisksAmount) //碎屏金额   真实支付的碎屏价格
                .screenRisksType(screenStr)//碎屏状态
                .build();
        try {
            orderMapper.insert(aiZUJiOrder);
            return aiZUJiOrder.getId();
        }catch (Exception e){

            logger.info("添加错误" + e.getMessage());
            throw e; // 重新抛出，确保事务回滚
        }
    }
    //区分颜色和存储
    public MaterialSpec getMaterialSpec(String[] spec){
        String colour = null;
        String suk = null;
        //logger.info("商品属性："+spec);
        for(String part : spec){
            String trimmedPart = part.trim();
            if(trimmedPart.contains("色")||trimmedPart.contains("典") || trimmedPart.contains("青")){
                colour = trimmedPart;
                //logger.info("颜色："+colour);
            }else{
                suk = trimmedPart;
                //logger.info("SKU："+suk);
            }
        }
        return new MaterialSpec(colour,suk);
    }
}